#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/11 17:47
# @Author : cjw
import json
from typing import Union

from mitmproxy.http import HTTPFlow, HTTPResponse

url_part1 = 'https://stock.xueqiu.com/v5/stock/batch/quote.json?_t='
url_part2 = 'x='


class Rewrite:
    """Rewrite 实现股票颜色变换的的边界值测试"""

    def response(self, flow: HTTPFlow):
        current_url = flow.request.url  # 当前url
        # url匹配规则
        if url_part1 in current_url and url_part2 in current_url:
            data = json.loads(flow.response.text)  # 获取响应数据
            data_intercept = data['data']['items'][:5]  # 截取5个股票数据

            # # 修改公司名称
            # for i, cm_data in enumerate(data_intercept):
            #     cm_data['quote']['name'] = f'zmyc{1000 + i}'

            # 修改公司当前价格
            # current = ['+0.01', '-0.01', '0.00', '+99999999999999999999999.99', '-99999999999999999999999.99']
            # for i, cm_data in enumerate(data_intercept):
            #     cm_data['quote']['current'] = current[i]

            # 修改公司股票咱跌幅，实现颜色变换
            percent = ['+0.01', '-0.01', '0.00', '+99999999999999999999999.99', '-99999999999999999999999.99']
            for i, cm_data in enumerate(data_intercept):
                cm_data['quote']['percent'] = percent[i]

            # 替换响应值
            flow.response.text = json.dumps(data)


class MapLocalMit:
    """MapLocal 修改雪球行情页的股票名称改为自己的名字"""

    def request(self, flow: HTTPFlow):
        """request事件中的修改的响应字段数据，在response事件中修改时，会被覆盖"""
        current_url = flow.request.url

        # url匹配规则
        if url_part1 in current_url and url_part2 in current_url:
            with open('quote.json', encoding='utf-8') as f:
                # 请求中response属性为空，需要手动创建一个返回对象
                # response事件中不做处理，返回数据会在request事件中的数据被覆盖
                flow.response = HTTPResponse.make(200, f.read())


class RecursionFloat:
    """倍增股票价格"""

    def response(self, flow: HTTPFlow):
        current_url = flow.request.url
        # url 匹配规则
        if url_part1 in current_url and url_part2 in current_url:
            rsp = json.loads(flow.response.text)
            data = self._recursion_float(rsp, 10)

            # 替换返回结果
            flow.response.text = json.dumps(data)

    def _recursion_float(self, data, nums: Union[int, float] = 1):
        """
        在原始数据基础上，递归倍增float数据类型的值
        :param data: 原始数据
        :param nums: 倍增的倍数
        :return:
        """
        if isinstance(data, dict):
            for k, v in data.items():
                data[k] = self._recursion_float(v, nums)
        elif isinstance(data, list):
            data = [self._recursion_float(item, nums) for item in data]
        elif isinstance(data, float):
            data = data * nums
        else:
            data = data
        return data


# 1、addons:插件；2、列表中包含实例对象
addons = [Rewrite(), MapLocalMit(), RecursionFloat()]

if __name__ == '__main__':
    from mitmproxy.tools.main import mitmdump

    # 使用debug模式启动mitmdump, __file__：表示当前文件
    mitmdump(['-p', '8888', '-s', __file__])
